<template>
  <div class="common-table-component">
    <!-- 集成Empty组件 -->
    <Empty
      v-if="showEmpty"
      :loading="loading"
      :loadError="loadError"
      :errorMessage="errorMessage"
      :dataList="data"
      :emptyTextKey="emptyTextKey"
      :useSimpleImage="useSimpleImage"
      @retry="handleRetry"
    />
    
    <!-- 有数据或正在加载时显示表格 -->
    <template v-else>
      <a-table
        :columns="columns"
        :data-source="data"
        :loading="loading"
        :pagination="false"
        :row-selection="enableRowSelection ? { selectedRowKeys, onChange: handleSelectionChange } : undefined"
        :row-key="rowKey"
        @change="handleTableChange"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ column, text, record }">
          <!-- 状态列插槽 -->
          <template v-if="column.key === 'status' && enableStatusColumn">
            <div class="status-tag">
              <a-switch
                :checked="getRecordStatus(record)"
                :loading="record.statusLoading"
                @change="(checked: any) => handleStatusChange(record.id, checked)"
              />
            </div>
          </template>
          
          <!-- 操作列插槽 -->
          <template v-else-if="column.key === 'action'">
            <div class="action-column">
              <slot name="action" :record="record"></slot>
            </div>
          </template>
          
          <!-- 提供自定义插槽 -->
          <template v-else>
            <slot :name="column.dataIndex || column.key" :text="text" :record="record" :column="column"></slot>
          </template>
        </template>
      </a-table>
      
      <!-- 分页组件 -->
      <Pagination
        v-if="pagination && showPagination"
        :total="pagination.total || 0"
        :current="pagination.current || 1"
        :pageSize="pagination.pageSize || 10"
        :showQuickJumper="showQuickJumper"
        :showSizeChanger="showSizeChanger"
        @change="handlePaginationChange"
      />
    </template>
  </div>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import type { TableColumnsType, TablePaginationConfig } from 'ant-design-vue'
import type { Key } from 'ant-design-vue/es/table/interface'
import Pagination from '@/components/common/Pagination.vue'
import Empty from '@/components/common/Empty.vue'

defineOptions({
  name: 'BaseTable'
})

// Props定义
const props = withDefaults(defineProps<{
  columns: TableColumnsType
  data: any[]
  loading?: boolean
  pagination?: TablePaginationConfig
  selectedRowKeys?: Key[]
  rowKey?: string | ((record: any) => string)
  enableRowSelection?: boolean
  enableStatusColumn?: boolean
  showPagination?: boolean
  showQuickJumper?: boolean
  showSizeChanger?: boolean
  getRecordStatus?: (record: Record<string, any>) => boolean
  // Empty组件相关属性
  loadError?: boolean
  errorMessage?: string
  emptyTextKey?: string
  useSimpleImage?: boolean
  // 是否始终显示表格（即使没有数据）
  alwaysShowTable?: boolean
}>(), {
  loading: false,
  data: () => [],
  pagination: () => ({}),
  selectedRowKeys: () => [],
  rowKey: 'id',
  enableRowSelection: true,
  enableStatusColumn: false,
  showPagination: true,
  showQuickJumper: true,
  showSizeChanger: true,
  getRecordStatus: (record: Record<string, any>) => record.status === 1,
  loadError: false,
  errorMessage: '',
  emptyTextKey: 'common.emptyData',
  useSimpleImage: true,
  alwaysShowTable: false
})

// Emits定义
const emit = defineEmits<{
  (e: 'selection-change', keys: Key[]): void
  (e: 'table-change', pagination: TablePaginationConfig, filters?: any, sorter?: any): void
  (e: 'status-change', id: string, status: boolean | number): void
  (e: 'pagination-change', page: number, pageSize: number): void
  (e: 'retry'): void
}>()

// 是否显示Empty组件
const showEmpty = computed(() => {
  if (props.alwaysShowTable) return false
  return props.loadError || (props.data.length === 0 && !props.loading)
})

/**
 * 表格选择变更处理
 * @param keys 选中的行键值
 */
const handleSelectionChange = (keys: Key[]) => {
  emit('selection-change', keys)
}

/**
 * 表格分页、排序、筛选变更处理
 */
const handleTableChange = (pagination: TablePaginationConfig, filters: any, sorter: any) => {
  emit('table-change', pagination, filters, sorter)
}

/**
 * 处理自定义分页变更
 */
const handlePaginationChange = (page: number, pageSize: number) => {
  const newPagination = {
    ...props.pagination,
    current: page,
    pageSize: pageSize
  }
  emit('pagination-change', page, pageSize)
  emit('table-change', newPagination)
}

/**
 * 状态变更处理
 */
const handleStatusChange = (id: string, checked: boolean) => {
  emit('status-change', id, checked)
}

/**
 * 重试处理
 */
const handleRetry = () => {
  emit('retry')
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/views/common.scss';
</style> 